package org.zsl.dao;

import java.sql.*;

public class DBUtil {

    private static   Connection connection = null;
    private static ResultSet resultSet = null;
    private static PreparedStatement preparedStatement=null;

    private static String url = "jdbc:mysql://localhost:3306/demo";
    private static String userame = "root";
    private static String password = "123456";
    private static  String driver="com.mysql.cj.jdbc.Driver";


    public static  Connection createConnection(){


        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,userame,password);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return  connection;
    }


    public static ResultSet excuteQuery(String sql,Object[] params){

         connection =createConnection();

        try {
          preparedStatement=    connection.prepareStatement(sql);

            for (int i = 0; i < params.length; i++) {

                preparedStatement.setObject(i+1,params[i]);
            }

            resultSet = preparedStatement.executeQuery();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return  resultSet;

    }
    
    public static  int excuteUpate(String sql,Object[] params){

        connection = createConnection();
        int affected=0;

        try {
            preparedStatement = connection.prepareStatement(sql);

            for (int i = 0; i <params.length ; i++) {

                  preparedStatement.setObject(i+1,params[i]);

            }
            affected = preparedStatement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  affected;
    }
}
